package com.atguigu.blog;

import org.apache.commons.lang3.RandomStringUtils;
import redis.clients.jedis.Jedis;

import java.util.Random;

public class PhoneCode {

    public static void main(String[] args) {
//        String random = RandomStringUtils.randomNumeric(6);
//        System.out.println(random);
//        String code = PhoneCode.getCode();
//        System.out.println(code);
        String code = PhoneCode.getCode();
        verifyCode("999");
//        getRedisCode("16619009888", "140070");
    }

    // 生成6位数字随机数
    public static String getCode() {
        Random random = new Random();
        String code = "";
        for (int i=0;i<6;i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }

    // 每个手机每天只能发生三次, 验证码放入redis中，设置过期时间
    public static void verifyCode(String phone) {
        Jedis jedis = new Jedis("10.211.55.10", 6379);
        Long ttl = jedis.ttl("2000");
        // 拼接key
        // 手机号发送次数
        String countKey = "VerifyCode"+phone+":count";
        // 验证码key
        String codeKey = "VerifyCode"+phone+":code";
        // 每个手机每天只能发生三次
        String count = jedis.get(countKey);
        System.out.println(count);
        if (count==null) {
            // 没有发送过
            // 设置发送次数是1
            jedis.setex(countKey, 24*60*60, "1");
        } else if (Integer.parseInt(count)<=2){
            // 发送次数+1
            jedis.incr(codeKey);
        } else if (Integer.parseInt(count)>2){
            // 已发送了三次
            System.out.println("今天发送次数已经超过了3次");
            jedis.close();
        }

        // 发送验证码放入redis里
        String vcode = getCode();
        jedis.setex(codeKey, 120, vcode);
        jedis.close();
    }

    // 验证码校验
    public static void getRedisCode(String phone, String code) {
        // get reids code
        Jedis jedis = new Jedis("10.211.55.10", 6379);
        String codeKey = "VerifyCode"+phone+":code";
        String redisCode = jedis.get(codeKey);
        if (redisCode.equals(code)) {
            System.out.println("成功！");
        } else {
            System.out.println("失败！");
        }
    }
}
